package com.yubest.junit.encrypt.symmetric;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * 对称加密 des
 *
 * @Author: hweiyu
 * @Date: 2022/11/11 15:44
 */
public class Des {

    private static final String ALGORITHM = "DES";

    /**
     * 加密
     *
     * @param data
     * @param key
     * @return
     */
    public static String encrypt(String data, String key) {
        byte[] res = exec(Cipher.ENCRYPT_MODE, data.getBytes(), key.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(res);
    }

    /**
     * 解密
     *
     * @param data
     * @param key
     * @return
     */
    public static String decrypt(String data, String key) {
        byte[] bytes = Base64.getDecoder().decode(data);
        byte[] res = exec(Cipher.DECRYPT_MODE, bytes, key.getBytes());
        assert res != null;
        return new String(res, StandardCharsets.UTF_8);
    }

    private static byte[] exec(int mode, byte[] data, byte[] key) {
        try {
            // 强随机数生成器 (RNG)
            SecureRandom random = new SecureRandom();
            // DESKeySpec是一个成加密密钥的密钥内容的（透明）规范的接口。
            DESKeySpec desKey = new DESKeySpec(key);
            // 创建一个密匙工厂，然后用它把DESKeySpec转换成
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
            // 得到密钥对象SecretKey
            SecretKey securekey = keyFactory.generateSecret(desKey);
            // Cipher对象实际完成加密操作
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            // 用密匙初始化Cipher对象
            cipher.init(mode, securekey, random);
            // 现在，获取数据并加密，正式执行加密操作
            return cipher.doFinal(data);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }

}
